// pages/add/index.js
const app = getApp();
Page({

     /**
      * 页面的初始数据
      */
     data: {
          userInfo: {},
          rmb_reward_single: [],
          mag_reward_single: [],
          rmb_reward_all: 0,
          mag_reward_all: 0,
          rmb_index: 0,
          mag_index: 0,
          userInfo: {},
          imgs: [], //上传图片列表
          is_wxpay: 0,
          redbagCount: 0,
          style: {},
          first_is_red: false, //第一张照片从前是不是个红包照片呀
     },

     /**
      * 生命周期函数--监听页面加载
      */
     onLoad: function (options) {
          let that = this;
          //是否开启微信支付
          app.connect('index/setting', {}, function (res) {
               that.setData({
                    is_wxpay: res.is_wxpay
               })
          });
          //加载打赏价格配置
          app.connect("index/reward_config", [], function (res) {
               that.setData({
                    rmb_reward_single: res.rmb,
                    mag_reward_single: res.mag
               });
          });
          //登录
          app.login(function (userInfo) {
               app.checkMobile(userInfo.data);
               that.setData({
                    userInfo: userInfo.data
               })
          })
     },

     /**
      * 用户点击右上角分享
      */
     onShareAppMessage: function () {

     },
     RmbPickerChange: function (e) {
          this.setData({
               rmb_index: e.detail.value
          })
          this.reward_all()
     },
     MagPickerChange: function (e) {
          this.setData({
               mag_index: e.detail.value
          })
          this.reward_all()
     },
     /**
      * 返回红包照片数量
      */
     redbagCount: function () {
          var count = 0;
          var imgs = this.data.imgs;
          for (var x in imgs) {
               if (imgs[x].type == 2) {
                    count++;
               }
          }
          this.setData({
               redbagCount: count
          });
          return count;
     },
     /**
      * 计算整组照片
      */
     reward_all: function () {
          this.setData({
               rmb_reward_all: this.data.rmb_reward_single[this.data.rmb_index] * this.redbagCount(),
               mag_reward_all: this.data.mag_reward_single[this.data.mag_index] * this.redbagCount()
          });
     },
     /**
      * 点击发布
      */
     submit: function (e) {
          var describe = e.detail.value.describe;
          let that = this;
          let formId = e.detail.formId;
          if (that.data.imgs.length - that.redbagCount() <= 0) {
               wx.showToast({
                    title: '至少上传一张普通照片',
                    icon: 'none'
               })
               return false;
          } else if (describe.length == 0) {
               wx.showToast({
                    title: '请输入描述内容',
                    icon: 'none'
               })
               return false;
          } else if (describe.length > 150) {

               wx.showToast({
                    title: '描述不能超过150个字',
                    icon: 'none'
               })
               return false;
          } else if (that.data.imgs[0].type == 2) {
               wx.showToast({
                    title: '第一张照片必须是普通照片',
                    icon: 'none'
               })
               return false;
          }

          wx.showLoading({
               title: '加载中...',
          })
          //生成内容
          app.connect("account/send", {
               uid: that.data.userInfo.uid,
               openid: that.data.userInfo.openId,
               describe: describe, //，描述
               rmb_reward_single: that.data.rmb_reward_single[that.data.rmb_index],
               mag_reward_single: that.data.mag_reward_single[that.data.mag_index],
               rmb_reward_all: that.data.rmb_reward_all,
               mag_reward_all: that.data.mag_reward_all,
               formId: formId
          }, function (res) {
               var content_id = res.content_id;
               app.uploadimg({
                    url: app.globalData.url + 'account/upload',
                    path: that.data.imgs, //这里是选取的图片的地址数组
                    data: {
                         uid: that.data.userInfo.uid,
                         openid: that.data.userInfo.openId,
                         content_id: content_id
                    }
               });

               //生成小程序码
               app.connect('account/getQrcode', {
                    uid: that.data.userInfo.uid,
                    openid: that.data.userInfo.openId,
                    content_id: content_id
               }, function (res) {
                    console.log(res);
               });

               setTimeout(function () {
                    wx.hideLoading()
                    wx.redirectTo({
                         url: 'success?content_id=' + content_id
                    })
               }, 1000);


          });

     },
     chooseImg: function () {
          let that = this;
          if (that.data.imgs.length >= 9) {
               wx.showToast({
                    title: '最多上传9张照片',
                    icon: 'none'
               })
               return false;
          }

          wx.showActionSheet({
               itemList: ['普通照片', '打赏照片'],
               success: function (res) {
                    //照片类型 1.普通照片 2.红包照片
                    var type = res.tapIndex + 1;
                    if (type == 3) {
                         return false;
                    }
                    wx.chooseImage({
                         count: 9 - that.data.imgs.length,
                         sizeType: ['compressed'],
                         sourceType: ['album', 'camera'],
                         success: function (res) {
                              var tempFiles = res.tempFiles;
                              // tempFiles.reverse(); //数组反转
                              for (var x in tempFiles) {
                                   if (x == 0 && that.data.imgs.length == 0 && type == 2) {
                                        tempFiles[x].type = 1;
                                        that.setData({
                                             first_is_red: true
                                        });
                                        wx.showToast({
                                             title: '第一张照片必须是普通照片，已经自动转换成普通照片',
                                             icon: 'none'
                                        })
                                   } else {
                                        tempFiles[x].type = type;
                                   }

                                   console.log(tempFiles[x].path);
                              }
                              var tempFilePaths = that.data.imgs;
                              that.setData({
                                   imgs: tempFilePaths.concat(tempFiles)
                              });
                              that.reward_all()
                              return false;
                         },
                         fail: function (res) {
                              console.log(res);
                         }
                    })
               },
               fail: function (res) {
                    console.log(res.errMsg)
               }
          })

     },
     /**
      * 删除图
      */
     delImg: function (e) {
          var that = this;
          var index = e.target.dataset.index;
          if(that.data.imgs.length <= 1) {
               this.setData({
                    imgs: []
               });

          }
          if (that.data.imgs.length > 1) {
               if (index == 0 && that.data.imgs[1].type == 2) {
                    var imgs = that.data.imgs;
                    imgs[1].type = 1;
                    that.setData({
                         imgs: imgs
                    });
                    wx.showToast({
                         title: '第一张照片必须是普通照片，已经自动转换成普通照片',
                         icon: 'none'
                    })
               }
          }

          this.data.imgs.splice(index, 1)
          this.setData({
               imgs: this.data.imgs
          });
          
          console.log(this.data.imgs);
          this.reward_all()
     },
     /**
      * 预览上传的图
      */
     yulan: function (e) {
          let that = this;
          var path = e.currentTarget.dataset.path;
          var imgs = [];
          var imgs_data = that.data.imgs;
          for (var x in imgs_data) {
               imgs.push(imgs_data[x].path)
          }
          wx.previewImage({
               current: path, // 当前显示图片的http链接
               urls: imgs // 需要预览的图片http链接列表
          })
        //  console.log('预览照片');
     },
     change: function (e) {

          var pageX = e.changedTouches[0].pageX;
          var pageY = e.changedTouches[0].pageY;
          var index = e.currentTarget.dataset.index;
          let that = this;
          var style = [];
          for (var i = 0; i < that.data.imgs.length; i++) {
               style[i] = 1;
          }
          style[index] = "position:absolute;z-index:100;left:" + (pageX - 33) + "px;top:" + (pageY - 33) + "px";
          // that.setData({

          // })
          that.setData({
               style: style
          });

     },
     changend: function (e) {
          let that = this;
          var index = e.currentTarget.dataset.index;
          var pageX = e.changedTouches[0].pageX;
          var pageY = e.changedTouches[0].clientY;
          var query = wx.createSelectorQuery()
          query.selectAll('.picimg').boundingClientRect()
          query.selectViewport().scrollOffset()
          query.exec(function (res) {
               console.log(res);
               for (var x in res[0]) {
                  
                  
                    if ((pageX >= res[0][x].left && pageX <= (res[0][x].left + res[0][x].width)) && (pageY >= res[0][x].top && pageY <= (res[0][x].top + res[0][x].height))) {
                         
                         var bei_index = res[0][x]['dataset']['index']; //被置换图片的index
                         var imgs = that.data.imgs;
                         var cun = imgs[index];
                         //如果置换后的图还是自己则不继续
                         if(bei_index == index) {
                              return false;
                         }
                         imgs[index] = imgs[bei_index];
                         imgs[bei_index] = cun;
                         //被置换照片从前是红包照片
                         if (bei_index == 0) {

                              if (that.data.first_is_red == true) {
                                   imgs[index].type = 2;
                              }
                              if (cun.type == 1) {
                                   that.setData({
                                        first_is_red: false
                                   });

                              } else {

                                   that.setData({
                                        first_is_red: true
                                   });

                              }
                         }
                         if (index == 0) {
                              if (that.data.first_is_red == true) {
                                   imgs[bei_index].type = 2;
                              }
                              if (imgs[index].type == 2) {
                                   that.setData({
                                        first_is_red: true
                                   });
                              } else {
                                   that.setData({
                                        first_is_red: false
                                   });
                              }
                         }
                         console.log(index);
                         if (imgs[0].type == 2) {
                              imgs[0].type = 1;
                              wx.showToast({
                                   title: '第一张照片必须是普通照片，已经自动转换成普通照片',
                                   icon: 'none'
                              })
                              //
                         }
                         that.setData({
                              imgs: imgs
                         });
                    }

               }
          })

          that.setData({
               style: []
          });
     }
})